package com.backend.demo1.services;

import com.backend.demo1.config.ApiException;
import com.backend.demo1.mapper.MatchMapper;
import com.backend.demo1.models.Match;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MatchService {

    @Autowired
    private MatchMapper matchMapper;

    // 创建比赛信息
    public Match createMatch(Match match) {
        try {
            matchMapper.insertMatch(match);
            return match; // 返回插入后的比赛对象
        } catch (Exception e) {
            throw new ApiException(500, "创建比赛失败: " + e.getMessage());
        }
    }

    // 获取所有比赛信息列表
    public List<Match> getMatchesList() {
        try {
            return matchMapper.findAllMatchesList();
        } catch (Exception e) {
            throw new ApiException(500, "获取比赛列表失败: " + e.getMessage());
        }
    }

    // 根据 ID 获取比赛信息
    public Match getMatchById(Long id) {
        try {
            Match match = matchMapper.findMatchById(id);
            if (match == null) {
                throw new ApiException(404, "比赛不存在");
            }
            return match;
        } catch (Exception e) {
            throw new ApiException(500, "获取比赛失败: " + e.getMessage());
        }
    }

    // 更新比赛信息
    public void updateMatch(Long id, Match inputMatch) {
        try {
            Match existingMatch = matchMapper.findMatchById(id);
            if (existingMatch == null) {
                throw new ApiException(404, "比赛不存在");
            }
            inputMatch.setMatchId(id); // 确保 ID 一致
            matchMapper.updateMatch(inputMatch);
        } catch (Exception e) {
            throw new ApiException(500, "更新比赛失败: " + e.getMessage());
        }
    }

    // 删除比赛信息
    public void deleteMatch(Long id) {
        try {
            Match match = matchMapper.findMatchById(id);
            if (match == null) {
                throw new ApiException(404, "比赛不存在");
            }
            matchMapper.deleteMatchById(id);
        } catch (Exception e) {
            throw new ApiException(500, "删除比赛失败: " + e.getMessage());
        }
    }
}